﻿#include "videodealthread.h"
#include <QDebug>
#include <QFileInfo>
#include <QDir>

//#include <opencv2/core/core.hpp>
//#include "opencv2/highgui/highgui.hpp"
//#include <opencv2/imgproc/imgproc.hpp>
//#include "opencv2/videoio/videoio_c.h"
#include "opencv2/opencv.hpp"

#include <windows.h>

VideoDealThread::VideoDealThread(const QString & filename, const QString &output_dir,
                                 unsigned long long core, QObject *parent)
    : QThread{parent}, filename_(filename), output_dir_(output_dir), ok_count(0), core_(core)
{

}

void VideoDealThread::run()
{
    SetThreadAffinityMask(GetCurrentThread(), core_);

    if (filename_.size() == 0)
    {
        emit file_empty_error();
        return;
    }

    //cv::VideoCapture capture;

    //bool ret = capture.open("C:\\Users\\WHD\\Desktop\\1.mp4");
    cv::VideoCapture capture(filename_.toStdString());
    
    if (!capture.isOpened())
    {
        capture.release();
        emit file_not_exist_error(filename_);
        return;
    }

    cv::Size new_size(190, capture.get(cv::CAP_PROP_FRAME_HEIGHT) / (capture.get(cv::CAP_PROP_FRAME_WIDTH) / 190));

    auto frame_number = capture.get(cv::CAP_PROP_FRAME_COUNT);  // 获取视频针数目(一帧就是一张图片)
    auto fps = capture.get(cv::CAP_PROP_FPS);  // 获取每针视频的频率
    frame_time = 400 / fps;
    qDebug() << "fps = " << fps;
    qDebug() << "1000 / fps = " << 400 / fps;
    qDebug() << "frame_time = " << frame_time;

    //创建写入对象,需要指定，帧率和视频宽高
    cv::VideoWriter writer;

    // 设置输出文件
    QFile file(output_dir_.append("/").append(filename_.section("/", -1).section(".", 0, 0)).append(".svd"));
    file.open(QIODevice::WriteOnly);

    cv::Mat image;
    while (capture.read(image))
    {
        cv::resize(image, image, new_size);
        cv::cvtColor(image, image, cv::COLOR_BGR2GRAY);

        QByteArray frame_data;
        for (int y = 0; y < image.rows; ++y)
        {
            for (int x = 0; x < image.cols; ++x)
            {
                frame_data.push_back(image.at<unsigned char> (y, x) / 16);
            }
            frame_data.append(16);
        }
        ++ok_count;
        frame_data.append(17);
        file.write(frame_data);
        emit change_jin_du(ok_count * 100 / frame_number);
    }

    //释放
    capture.release();
    file.close();

    emit deal_ok();
}

VideoDealThread::~VideoDealThread()
{
    qDebug() << "VideoDealThread 销毁了";
}
